package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"nm/cache"
	"nm/models"
	"nm/pkg"
	"time"
)

type UserMainController struct {
	beego.Controller
}
type Res struct {
	Code int         `json:"Code"`
	Msg  string      `json:"Msg"`
	Data interface{} `json:"Data"`
}

func (c *UserMainController) Register() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "参数为空",
			Data: nil,
		}
		c.ServeJSON()
	}
	var user models.User
	pwd := pkg.Md5(password)
	user.Username = username
	user.Password = pwd
	err := models.DB.Create(&user).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "注册失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "注册成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *UserMainController) Login() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "参数为空",
			Data: nil,
		}
		c.ServeJSON()
	}
	var user models.User

	if user.ID == 0 {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "用户不为空",
			Data: nil,
		}
		c.ServeJSON()
	}
	key := "login_error"
	errcount, _ := cache.Rdb.Get(cache.Ctx, key).Int()
	if errcount >= 3 {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "密码错误3次封禁两小时",
			Data: nil,
		}
		c.ServeJSON()
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, key)
		if errcount == 2 {
			cache.Rdb.Expire(cache.Ctx, key, time.Hour*3)
		}
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "登录失败",
			Data: nil,
		}
		c.ServeJSON()
	}
}
